/**
 * Copyright (c) 2006-2016 Huize Ltd. All Rights Reserved. 
 *  
 * This code is the confidential and proprietary information of   
 * Hzins. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with Huize,http://www.huize.com.
 *  
 */
package com.agan.concurrent;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author hz1412988
 * @date 2018年2月5日 下午2:40:26
 * @version
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
	/** 定义窗口个数 **/
	final CyclicBarrier cb = new CyclicBarrier(10, new Runnable() {

	    @Override
	    public void run() {
		System.out.println("人员全部到齐了，各自拍照留念，拍照结束，就开始吃饭。。。。");
	    }

	});

	ExecutorService executor = Executors.newCachedThreadPool();
	/** 模拟10个用户 **/
	for (int i = 1; i <= 10; i++) {
	    final int offset = i;
	    executor.execute(new Runnable() {

		@Override
		public void run() {
		    try {
			TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
			System.out.println(Thread.currentThread().getName() + "->" + offset + "到达聚餐地点，当前已有" + (cb.getNumberWaiting() + 1) + "人到达");
			// 阻塞
			cb.await();
			TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
			System.out.println(Thread.currentThread().getName() + "->" + offset + "吃完饭了，准备回家。。。。");
		    } catch (InterruptedException e) {
			e.printStackTrace();
		    } catch (BrokenBarrierException e) {
			e.printStackTrace();
		    }
		}

	    });
	}
	executor.shutdown();
    }
}
